/*
 * @Descripttion: 工具集
 * @version: 1.1
 * @LastEditors: sakuya
 * @LastEditTime: 2021年7月20日10:58:41
 */

import { notify } from '@/hooks/useMessage'
import cloneDeep from 'lodash/cloneDeep'
import cloneDeepWith from 'lodash/cloneDeepWith'
import throttle from '@/utils/throttle'
import dayjs from "dayjs";
const tool = { cloneDeepWith }
import  sysConfig from '@/config'
const escape=function (str) {
	if(!str) return str
	// 定义一个映射表，用于转换常见的HTML实体到对应的字符
	const htmlEntities = {
		'&amp;': '&',
		'&mdash;': '-',
		'&lt;': '<',
		'&gt;': '>',
		'&quot;': '\"',
		'&apos;': '\'',
		'&ldquo;': '“',
		'&rdquo;': '”'
	};

	// 使用正则表达式和映射表进行替换操作
	return str.replace(/&[a-z]+;/g, (entity) => htmlEntities[entity] || entity);
}
tool.escape=escape
tool.getText=function (value){
	if(!value) return ''
	return value.replace(/<[^>]+>/g, '').replace(/&nbsp;/ig, '').replace(/\s/g, '')
}

tool.copyText = (text, callback) => {
	const oInput = document.createElement('input')
	oInput.value = text
	document.body.appendChild(oInput)
	oInput.select()
	document.execCommand('Copy')
	document.body.removeChild(oInput)
	callback && callback()
	if (callback) {
		callback()
	} else {
		notify({ message: '复制成功' })
	}
}
/* localStorage */
tool.data = {
	set(table, settings) {
		try {
			var _set = JSON.stringify(settings)
		} catch (e) {
			console.log(e)
		}
		return localStorage.setItem(table, _set)
	},
	get(table) {
		var data = localStorage.getItem(table)
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data
	},
	remove(table) {
		return localStorage.removeItem(table)
	},
	clear() {
		return localStorage.clear()
	}
}

/* sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set)
	},
	get(table) {
		var data = sessionStorage.getItem(table)
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data
	},
	remove(table) {
		return sessionStorage.removeItem(table)
	},
	clear() {
		return sessionStorage.clear()
	}
}

/* Fullscreen */
tool.screen = function(element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement)
	if (isFull) {
		if (document.exitFullscreen) {
			document.exitFullscreen()
		} else if (document.msExitFullscreen) {
			document.msExitFullscreen()
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen()
		} else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen()
		}
	} else {
		if (element.requestFullscreen) {
			element.requestFullscreen()
		} else if (element.msRequestFullscreen) {
			element.msRequestFullscreen()
		} else if (element.mozRequestFullScreen) {
			element.mozRequestFullScreen()
		} else if (element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen()
		}
	}
}

/* 复制对象 */
tool.objCopy = function(obj) {
	return cloneDeep(obj)
}
/* 获取当前时间 */
tool.getNowTime = (fmt = 'yyyyMMddhhmmss') => {
	return tool.dateFormat(new Date().getTime(), fmt)
}
function filterUrl(url){
	if(url?.indexOf('http:')!=-1){
		return  url
	}
	return sysConfig.IMG_URL  +url
}
tool.filterUrl=filterUrl
tool.richTextWithUrls=(richText)=>{
	if(!richText) return richText
	richText=escape(richText)
	// 匹配图片URL的正则表达式
	const imageRegex = /<img.*?src="(.*?)"/g;

	// 匹配视频URL的正则表达式
	const videoRegex = /<video.*?src="(.*?)"/g;

	// 替换图片URL
	const replacedImageText = richText.replace(imageRegex, (match, url) => {
		return `<img src="${filterUrl(url)}" `;
	});

	// 替换视频URL
	const replacedVideoText = replacedImageText.replace(videoRegex, (match, url) => {
		return `<video src="${filterUrl(url)}" controls `;
	});

	return replacedVideoText;
}
tool.richTextWithUrlsRemove=(richText)=>{
	if(!richText) return richText
	richText=escape(richText)
	// 匹配图片URL的正则表达式
	const imageRegex = /<img.*?src="(.*?)".*?>/g;

	// 匹配视频URL的正则表达式
	const videoRegex = /<video.*?src="(.*?)".*?>/g;
	// 匹配视频URL的正则表达式
	const tableRegex =  /<table.*?/g;

	// 替换图片URL
	const replacedImageText = richText.replace(imageRegex, (match, url) => {
		return ``;
	});

	// 替换视频URL
	const replacedVideoText = replacedImageText.replace(videoRegex, (match, url) => {
		return ``;
	});
	// 替换表格
	const tableText = replacedImageText.replace(tableRegex, (match, url) => {
		return `<table style="display:none"`;
	});
	return tableText;
}
/* 日期格式化 */
tool.dateFormat = function(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	return  dayjs(date).format(fmt)
	return fmt
}

/**
 * 时间戳转为多久之前
 * @param String timestamp 时间戳
 * @param String | Boolean format 如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
 */
tool.timeFrom = function(dateTime = null, format = 'yyyy-mm-dd') {
	// 如果为null,则格式化当前时间
	if (!dateTime) dateTime = Number(new Date())
	// 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
	if (dateTime.toString().length == 10) dateTime *= 1000
	const timestamp = +new Date(Number(dateTime))

	const timer = (Number(new Date()) - timestamp) / 1000
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	let tips = ''
	switch (true) {
		case timer < 300:
			tips = '刚刚'
			break
		case timer >= 300 && timer < 3600:
			tips = parseInt(timer / 60) + '分钟前'
			break
		case timer >= 3600 && timer < 86400:
			tips = parseInt(timer / 3600) + '小时前'
			break
		case timer >= 86400 && timer < 2592000:
			tips = parseInt(timer / 86400) + '天前'
			break
		default:
			// 如果format为false，则无论什么时间戳，都显示xx之前
			if (format === false) {
				if (timer >= 2592000 && timer < 365 * 86400) {
					tips = parseInt(timer / (86400 * 30)) + '个月前'
				} else {
					tips = parseInt(timer / (86400 * 365)) + '年前'
				}
			} else {
				tips = tool.dateFormat(timestamp, format)
			}
	}
	return tips
}

/* 千分符 */
tool.groupSeparator = function(num) {
	num = num + ''
	if (!num.includes('.')) {
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
		return $1 + ','
	}).replace(/\.$/, '')
}
/**
 * 节流
 * @param {function} fun
 * @param {number} delay
 * @returns
 */
tool.throttle = throttle


export default tool
